package com.example.smartcity.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.example.smartcity.R;
import com.example.smartcity.bean.CommentBean;
import com.example.smartcity.bean.ResponseBean;
import com.example.smartcity.utils.APIConfig;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class VideoContentActivity extends AppCompatActivity {
    private static final String TAG = "VideoContentActivity";
    private VideoView videoView;
    private String video_url;
    private TextView videoAuthor;
    String video_author;
    private TextView videoTitle;
    String video_title;
    private TextView videoTime;
    String video_time;
    private MediaPlayer mediaPlayer;
    private int video_id;
    String url2;
    final String url = APIConfig.BASE_URL;
    private EditText comment_content;
    private ListView video_comment;
    private Button  btn_comment;
    private CommentBean commentBean;
    private CommentAdapter commentAdapter;
    private TextView no_video_comment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        video_id = intent.getIntExtra("videoid", 0);
        video_url = intent.getStringExtra("videourl");
        video_author = intent.getStringExtra("videoauthornick");
        video_time = intent.getStringExtra("videotime");
        video_title = intent.getStringExtra("videoname");
        Log.i(TAG, "onCreate: "+TAG);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_content);
        no_video_comment = findViewById(R.id.no_video_comment);
        videoView = findViewById(R.id.videoView);
        videoAuthor = findViewById(R.id.video_author);
        videoTime = findViewById(R.id.video_time);
        videoTitle = findViewById(R.id.video_title);
        btn_comment = findViewById(R.id.btn_comment);
        btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (comment_content.getText().toString().equals(null)||comment_content.getText().toString().equals("")){
                    Toast.makeText(VideoContentActivity.this, "评论不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    SendComment();
                    comment_content.setText("");
                    getNewsComment();
                }

            }
        });
        LinearLayout linearLayout = findViewById(R.id.linearLayout);
        comment_content = findViewById(R.id.comment_content);
        comment_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                btn_comment.setEnabled(false);
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0||s!=""||s.equals("")==false) {
                    // EditText中有内容
                    btn_comment.setEnabled(true);

                } else {
                    // EditText中没有内容
                    btn_comment.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        video_comment = findViewById(R.id.video_comment);//video_comment
        getNewsComment();

        //获取视频
        //拿到路径并播放
        //String videoPath1 = "http://10.7.89.104:8085/videos/Naraka-replay-20240505-09-48-39.mp4";
        videoView.setVideoURI(Uri.parse(APIConfig.BASE_URL+video_url));
        videoAuthor.setText(video_author);
        videoTitle.setText(video_title);
        videoTime.setText(video_time);
        //tv1.start();        //先别急着播放，而是通过设置下面代码，将画面定格在第0毫秒
        videoView.setOnPreparedListener(mp -> {
            mp.seekTo(0); // 将视频跳转到第0毫秒
        });
        //添加别的视频辅助控件
        MediaController mediaController1 = new MediaController(this);
        mediaController1.setAnchorView(videoView);
        videoView.setMediaController(mediaController1);
    }
    public void getNewsComment() {
    /*pageNum 当前页
    pressId 新闻编号
    pageSize*/
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(APIConfig.BASE_URL+"/press/getvideocomment?videoid="+video_id)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("请求失败：",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Gson gson = new Gson();
                            commentBean = gson.fromJson(result, CommentBean.class);
                            if (commentBean.getTotal()==0){
                                no_video_comment.setText("首评是我的啦嗨嗨嗨!!");
                            }
                            commentAdapter = new CommentAdapter();
                            video_comment.setAdapter(commentAdapter);
                            setListViewHeightBasedOnChildren(video_comment);
                            video_comment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    Toast.makeText(getApplication(),"点击了"+i,Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    });
                }
            }
        });
    }

    public void SendComment(){
        Log.i("发送评论","发送评论");
        SharedPreferences sharedPreferences = getSharedPreferences("token_data", MODE_PRIVATE);
        int tokenValue = sharedPreferences.getInt("token", 1);
        String content1 = comment_content.getText().toString().trim();
        SharedPreferences sp = this.getSharedPreferences("token_data",MODE_PRIVATE);
        int token = sp.getInt("token",0);
        OkHttpClient client = new OkHttpClient();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userId",tokenValue);
            jsonObject.put("pressId",1);
            jsonObject.put("content",content1);
            Log.i("videoid",video_id+"");
            jsonObject.put("videoid",video_id);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
        System.out.println(jsonObject.toString());
        Request request = new Request.Builder()
                .url(APIConfig.BASE_URL+"/press/pressvideocomment")
                .post(requestBody)
                .addHeader("Authorization",Integer.toString(token))
                .build();
        //System.out.println(APIConfig.BASE_URL+"/press/presscomment");
        Call call  = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("请求失败：",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    Gson gson = new Gson();
                    ResponseBean responseBean = gson.fromJson(result,ResponseBean.class);
                    String code = responseBean.getCode();
                    System.out.println(code);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("评论成功：",result);
                                Toast.makeText(getApplicationContext(),"评论成功："+result,Toast.LENGTH_LONG).show();
                                getNewsComment();
                                video_comment.setAdapter(commentAdapter);
                                video_comment.deferNotifyDataSetChanged();
//                                Intent intent = getIntent();
//                                finish();
//                                startActivity(intent);
                            }
                        });
                    }
                }
        });

    }
    public class CommentAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return commentBean.getRows().size();
        }
        @Override
        public Object getItem(int i) {
            return commentBean.getRows().get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            CommentAdapter.ViewHolder holder;
            if (view==null) {
                view = View.inflate(getApplicationContext(),R.layout.comment_item,null);
                holder = new ViewHolder();
                holder.comment_time = view.findViewById(R.id.comment_time);
                holder.comment_nick = view.findViewById(R.id.comment_nick);
                holder.comment_content = view.findViewById(R.id.comment_content);
                holder.comment_img = view.findViewById(R.id.comment_img);
                view.setTag(holder);
            } else {
                holder = (CommentAdapter.ViewHolder) view.getTag();
            }
            holder.comment_content.setText(commentBean.getRows().get(i).getComment_content());
            holder.comment_nick.setText(commentBean.getRows().get(i).getComment_nick());
            holder.comment_time.setText(commentBean.getRows().get(i).getComment_time());
            String url = commentBean.getRows().get(i).getComment_avatar();
            Log.i("commentavatar",APIConfig.BASE_URL+url);
            Glide.with(getApplicationContext()).load(APIConfig.BASE_URL+url).into(holder.comment_img);
            return view;
        }

        // ListView优化类
        class ViewHolder{
            TextView comment_time;
            TextView comment_nick;
            TextView comment_content;
            ImageView comment_img;
        }
    }
    public static void setListViewHeightBasedOnChildren(ListView listView){
        CommentAdapter commentAdapter = (CommentAdapter) listView.getAdapter();
        if (commentAdapter==null){
            return;
        }
        int totalHeight=0;
        // getCount() 获取返回数据项的数目
        for (int i=0;commentAdapter.getCount()>i;i++){
            View listItem = commentAdapter.getView(i,null,listView);
            // 计算子项View的宽高
            listItem.measure(0,0);
            // 统计所有子项的总高度
            totalHeight+=listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+(listView.getDividerHeight()*(commentAdapter.getCount()-1));
        listView.setLayoutParams(params);
    }

}